package a66weding.com.jiehuntong.activity.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeGeneralizeBean;
import a66weding.com.jiehuntong.beans.MyFriendGeneralizeBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.widgets.CircularImage;

/**
 * 这是我的界面下,我的推广好友界面
 * Created by Administrator on 2016/8/18.
 */
public class MeGeneralizeFriendActivity extends MeBaseActivity implements View.OnClickListener ,OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private RelativeLayout mHeaderRightRlay;
    private ListView mGeneralizeLv;
    private TextView mBTv;
    private TextView mETv;
    private String BData;// 起始日期
    private String EData;// 结束日期
    private ArrayList<MeGeneralizeBean.DataBean> mlist;
    private Intent intent;
    private Context context;
    private XRefreshView generalizeXrefreshview;
    private int pageIndex = 1;
    private int pageSize = 20;
    private MyAdapter adapter;
    private MyAdapterFriend adapterFriend;
    private ArrayList<MyFriendGeneralizeBean.DataBean> mlistFriend;
    private String source;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_generalize_friend);
        context = this;
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeGeneralizeFriendActivity", this);

        //        取得系统日期:
        Calendar c = Calendar.getInstance();
        int mCurrentYear = c.get(Calendar.YEAR);
        int mCurrentMonth = c.get(Calendar.MONTH);
        int mCurrentDay = c.get(Calendar.DAY_OF_MONTH);

        initview();
        BData = (mCurrentYear - 1) +"-" + (mCurrentMonth + 1) +"-" + mCurrentDay;
        EData = mCurrentYear +"-" + (mCurrentMonth + 1) +"-" + mCurrentDay;
        mBTv.setText(BData);
        mETv.setText(EData);
        if(source.equals("me")){
            mlist = new ArrayList<MeGeneralizeBean.DataBean>();
            adapter = new MyAdapter(mlist);
            mGeneralizeLv.setAdapter(adapter);
        } else if(source.equals("myFriend")){
            mlistFriend = new ArrayList<MyFriendGeneralizeBean.DataBean>();
            adapterFriend = new MyAdapterFriend(mlistFriend);
            mGeneralizeLv.setAdapter(adapterFriend);
        }
        initdata();
        EventBus.getDefault().register(this);
    }

    /**
     * 开始时间
     * @param event
     */
    @Subscribe
    public void onEvent(MeSetGeneralizeBDataActivity.BDataEvent event){
        if(event != null){
            mBTv.setText(event.year + "-" + event.month + "-" + event.day);
            BData = event.year + "-" + event.month + "-" + event.day;
            pageIndex = 1;
            initdata();
        }
    }

    /**
     * 结束时间
     * @param event
     */
    @Subscribe
    public void onEvent(MeSetGeneralizeEDataActivity.EDataEvent event){
        if(event != null){
            mETv.setText(event.year + "-" + event.month + "-" + event.day);
            EData = event.year + "-" + event.month + "-" + event.day;
            pageIndex = 1;
            initdata();
        }
    }

    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mBTv = (TextView) findViewById(R.id.tv_me_generalize_b_data);
        mETv = (TextView) findViewById(R.id.tv_me_generalize_e_data);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);
        mGeneralizeLv = (ListView) findViewById(R.id.lv_me_generalize);

        mBackContentTv.setText("返回");
        mHeaderRightRlay.setVisibility(View.GONE);

        mBackLay.setOnClickListener(this);
        mBTv.setOnClickListener(this);
        mETv.setOnClickListener(this);

        intent = getIntent();
        source = intent.getStringExtra("generalize");
        if(source.equals("me")){
            mHeaderTitleTv.setText("我的推广好友列表");
        } else if(source.equals("myFriend")){
            mHeaderTitleTv.setText("我的二级推广列表");
        }
        TextView generalizeNumTv = (TextView) findViewById(R.id.tv_generalize_num);
        generalizeNumTv.setText(intent.getStringExtra("generalizeContent"));


        generalizeXrefreshview = (XRefreshView) findViewById(R.id.generalize_xrefreshview);
        //是否允许下拉刷新
        generalizeXrefreshview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        generalizeXrefreshview.setPullLoadEnable(true);
        // 设置刷新完成以后，headerview固定的时间
        generalizeXrefreshview.setPinnedTime(1000);

        generalizeXrefreshview.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onLoadMore(boolean isSlience) {
                initdata();
            }
            @Override
            public void onRefresh() {
                super.onRefresh();
                pageIndex = 1;//刷新的时候第1页是最新数据
                initdata();
            }
        });
    }

    private void initdata() {
        String url;
        if(source.equals("me")){
            url= UrlDealUtil.getRealUrlNoIdApi(RequestCode.MEMBERTGLIST) + "&M_TG_CODE=" +
                DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No() + "&pageIndex=" + pageIndex +
                "&pageSize=" + pageSize + "&orderType=" + 1 + "&BDate=" + BData + "&EDate=" + EData;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    this, MeGeneralizeBean.class, RequestCode.MEMBERTGLIST);
            HttpHandleUtil.executeCommonPost(this,httpRequestBean);
        } else if(source.equals("myFriend")){
            url= UrlDealUtil.getRealUrlNoIdApi(RequestCode.MEMBERTGRJLIST) + "&M_TG_CODE=" +
                    DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_No() + "&pageIndex=" + pageIndex +
                    "&pageSize=" + pageSize + "&orderType=" + 1 + "&BDate=" + BData + "&EDate=" + EData;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    this, MyFriendGeneralizeBean.class, RequestCode.MEMBERTGRJLIST);
            HttpHandleUtil.executeCommonPost(this,httpRequestBean);
        }

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.llay_header_back: //点击返回，关闭界面
                finish();

                break;
            case R.id.tv_me_generalize_b_data: //点击设置开始时间
                intent.setClass(MeGeneralizeFriendActivity.this,MeSetGeneralizeBDataActivity.class);
                startActivity(intent);

                break;
            case R.id.tv_me_generalize_e_data: //点击设置结束时间
                intent.setClass(MeGeneralizeFriendActivity.this,MeSetGeneralizeEDataActivity.class);
                startActivity(intent);

                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof MeGeneralizeBean) {
            MeGeneralizeBean response = (MeGeneralizeBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    List<MeGeneralizeBean.DataBean>  datas = response.getData();
                    if(datas==null || datas.size() == 0){
                        CUtils.showToast("数据已全部加载完毕了");
                        if(pageIndex == 1){
                            mlist.clear();
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        if(pageIndex == 1){
                            mlist.clear();
                        }
                        pageIndex++;
                        mlist.addAll(datas);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }
        } else if (data instanceof MyFriendGeneralizeBean) {
            MyFriendGeneralizeBean response = (MyFriendGeneralizeBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    List<MyFriendGeneralizeBean.DataBean>  datas = response.getData();
                    if(datas==null || datas.size() == 0){
                        CUtils.showToast("数据已全部加载完毕了");
                        if(pageIndex == 1){
                            mlistFriend.clear();
                            adapterFriend.notifyDataSetChanged();
                        }
                    } else {
                        if(pageIndex == 1){
                            mlistFriend.clear();
                        }
                        pageIndex++;
                        mlistFriend.addAll(datas);
                        adapterFriend.notifyDataSetChanged();
                    }
                } else {
                    CUtils.showToast(response.getMsg());
                }
            }
        }

        generalizeXrefreshview.stopRefresh();//停止刷新
        generalizeXrefreshview.stopLoadMore();//停止加载更多
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("数据请求失败");
        generalizeXrefreshview.stopRefresh();//停止刷新
        generalizeXrefreshview.stopLoadMore();//停止加载更多
    }

    class MyAdapterFriend extends BaseAdapter {
        ArrayList<MyFriendGeneralizeBean.DataBean> mlist;

        public MyAdapterFriend(ArrayList<MyFriendGeneralizeBean.DataBean> mlist){
            this.mlist = mlist;
        }

        @Override
        public int getCount() {
            return mlist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder mHolder;
            if (convertView != null) {
                view = convertView;
                mHolder = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(getApplicationContext(), R.layout.item_me_generalize, null);
                mHolder = new ViewHolder();
                mHolder.mNameTv = (TextView) view.findViewById(R.id.tv_me_generalize_name);
                mHolder.mMoneyTv = (TextView) view.findViewById(R.id.tv_me_generalize_money);
                mHolder.mPic = (CircularImage) view.findViewById(R.id.iv_me_pic);
                view.setTag(mHolder);
            }
            mHolder.mNameTv.setText(mlist.get(position).getNvc_MemberName());
            mHolder.mMoneyTv.setText("¥" + mlist.get(position).getRealPay());
            mHolder.mPic.setImageResource(R.mipmap.default_img);
            if (!TextUtils.isEmpty(mlist.get(position).getNvc_Photo())){
                x.image().bind(mHolder.mPic, mlist.get(position).getNvc_Photo(), ImageOptionsUtil.getOptions120_120());
            }
            return view;
        }
    }

    class MyAdapter extends BaseAdapter {
        ArrayList<MeGeneralizeBean.DataBean> mlist;

        public MyAdapter(ArrayList<MeGeneralizeBean.DataBean> mlist){
            this.mlist = mlist;
        }

        @Override
        public int getCount() {
            return mlist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder mHolder;
            if (convertView != null) {
                view = convertView;
                mHolder = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(getApplicationContext(), R.layout.item_me_generalize, null);
                mHolder = new ViewHolder();
                mHolder.mNameTv = (TextView) view.findViewById(R.id.tv_me_generalize_name);
                mHolder.mMoneyTv = (TextView) view.findViewById(R.id.tv_me_generalize_money);
                mHolder.mPic = (CircularImage) view.findViewById(R.id.iv_me_pic);
                view.setTag(mHolder);
            }
            mHolder.mNameTv.setText(mlist.get(position).getNvc_Name());
            mHolder.mMoneyTv.setText("¥" + mlist.get(position).getMemberXFPrice());
            mHolder.mPic.setImageResource(R.mipmap.default_img);
            if (!TextUtils.isEmpty(mlist.get(position).getNvc_TitlePhoto())){
                x.image().bind(mHolder.mPic, mlist.get(position).getNvc_TitlePhoto(), ImageOptionsUtil.getOptions120_120());
            }
            return view;
        }
    }

    class ViewHolder{
        TextView mNameTv;
        TextView mMoneyTv;
        CircularImage mPic;
    }

}
